//
//  HZMSearchViewController.m
//  糖糖大魔王
//
//  Created by 韩震明 on 15/10/22.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "HZMSearchViewController.h"
#import "HZMIconDetailsVC.h"
#import "HZMSearchDetailsVC.h"
#import "HZMTableDetailsVC.h"
#import "HZMTableDetailsType1VC.h"

@interface HZMSearchViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UIScrollViewDelegate>

@property(nonatomic, retain) UISearchBar *searchBar;
@property(nonatomic, retain) UIView *accessoryView;
@property(nonatomic, retain) NSMutableArray *searchArr;
@property(nonatomic, retain) NSMutableArray *topicArr;
@property(nonatomic, retain) NSMutableArray *productArr;
@property(nonatomic, retain) UIView *searchView;
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UIScrollView *scrollView;
@property(nonatomic, retain) UICollectionView *collection;
@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) UIButton *leftButton;
@property(nonatomic, retain) UIButton *rightButton;
@property(nonatomic, retain) NSMutableArray *earthArr;

@end

@implementation HZMSearchViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.searchBar.hidden = NO;
//    [self.searchBar ]
    [self createNetWork];

}



- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.searchBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)dealloc
{
    [_searchArr release];
    [_collection release];
    [_searchBar release];
    [_accessoryView release];
    [_topicArr release];
    [_productArr release];
    [_tableView release];
    [_collectionView release];
    [_scrollView release];
    [_searchView release];
    [_leftButton release];
    [_rightButton release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setNavigation];
    
    
    [self createSearchBar];
    [self createCollection];
    
    
    self.searchArr = [NSMutableArray array];
    [self createData];
    
    [self createScrollView];
    [self createCollectionView];
    [self createTableView];
    self.searchView.hidden = YES;
    
    [self createNetWork];
}



#pragma mark Navigation Settin
- (void)setNavigation
{
    self.navigationItem.title = @"";
    
    self.navigationController.navigationBar.translucent = NO;
}



#pragma mark SearchBar Setting
- (void)createSearchBar
{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.navigationController.view.frame.size.width, 64)];
    self.searchBar.placeholder = @"搜索单品";
    self.searchBar.translucent = NO;
    [self.searchBar setBackgroundImage:[UIImage imageNamed:@"navigationBarImage.pdf"]];
    [self createAccessory];
//    self.searchBar.inputAccessoryView = self.accessoryView; // 设置者盖层
    
    self.searchBar.delegate = self;
    
    [self.navigationController.view addSubview:self.searchBar];
}

#pragma mark 遮盖层
- (void)createAccessory
{
//    self.accessoryView = [[UIButton alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64)];
    self.accessoryView = [[UIView alloc] initWithFrame:self.view.frame];
    _accessoryView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 64);
    [_accessoryView setBackgroundColor:[UIColor whiteColor]];
    [_accessoryView setAlpha:1];
    [self.view addSubview:self.accessoryView];
    [_accessoryView release];
//    [self controlAccessoryView:0];
}

// 控制遮罩层的透明度
- (void)controlAccessoryView:(float)alphaValue{
    
    [UIView animateWithDuration:0.2 animations:^{
        //动画代码
        [self.accessoryView setAlpha:alphaValue];
    }completion:^(BOOL finished){
        if (alphaValue<=0) {
            [self.searchBar resignFirstResponder];
            [self.searchBar setShowsCancelButton:NO animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            
        }
        
    }];
}

#pragma mark - UISearchBarDelegate 协议
// UISearchBar得到焦点并开始编辑时，执行该方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self.view bringSubviewToFront:self.accessoryView];
    if ([self.searchBar.text isEqualToString:@""]) {
        
        [self.searchBar setShowsCancelButton:YES animated:YES];
        //    [self.navigationController setNavigationBarHidden:YES animated:YES];
        //    [self controlAccessoryView:1];// 显示遮盖层。
        self.searchView.hidden = YES;
        self.accessoryView.hidden = NO;
    } else {
        self.searchBar.hidden = NO;
    }
    for (UIView *view in [[_searchBar.subviews lastObject] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            cancelBtn.tintColor = [UIColor blackColor];
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    return YES;
    
}

// 取消按钮被按下时，执行的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
    if ([self.searchBar.text isEqualToString:@""]) {
        self.accessoryView.hidden = YES;
    } else {
        self.accessoryView.hidden = NO;
//    [self controlAccessoryView:0];// 隐藏遮盖层。
    }
}

// 键盘中，搜索按钮被按下，执行的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
   
    
    NSLog(@"---%@",searchBar.text);
    self.searchView.hidden = NO;
    [self.searchBar resignFirstResponder];
    
    if (!([self.searchBar.text  isEqual: @""])) {
        
        [self createSearchData];
        [self saveHistory:self.searchBar.text];
    } else {
        self.searchView.hidden = YES;
    }
    
}

- (void)saveHistory:(NSString*)str
{

    NSUserDefaults *userDefault = [[NSUserDefaults alloc] init];
    if ([userDefault boolForKey:@"search"]) {
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:str];
        [userDefault setObject:arr forKey:@"search"];
    }else{
        NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[userDefault objectForKey:@"search"]];
        [arr1 addObject:str];
        [userDefault setObject:arr1 forKey:@"search"];
    }
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 150, 150, 100)];
//    [self.accessoryView addSubview:label];
//    [label release];
//    label.text = [[userDefault objectForKey:@"search"] lastObject];,
    NSLog(@"%@ ", [userDefault objectForKey:@"search"]);
    
}

// 当搜索内容变化时，执行该方法。很有用，可以实现时实搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.searchView.hidden = NO;
    NSLog(@"textDidChange---%@", [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
    
    if (!([self.searchBar.text  isEqual: @""])) {
        
        [self createSearchData];
    } else {
        self.searchView.hidden = YES;
    }
    
}



#pragma mark ScrollVIew
- (void)createScrollView
{
    self.searchView = [[UIView alloc] initWithFrame:self.accessoryView.frame];
    self.searchView.backgroundColor = [UIColor whiteColor];
    [self.accessoryView addSubview:self.searchView];
    [_searchView release];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 54, WIDTH, HEIGHT - 54)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.searchView addSubview:self.scrollView];
    [_scrollView release];
    
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    
    self.scrollView.contentSize = CGSizeMake(2 * WIDTH, 0);
    
    [self setButton];
//    [self createTableView];
//    [self createCollectionView];
}

#pragma mark ScrollView Delegate Method
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x == 0) {
        self.leftButton.backgroundColor = [UIColor cyanColor];
        self.rightButton.backgroundColor = [UIColor whiteColor];
    } else {
        self.rightButton.backgroundColor = [UIColor cyanColor];
        self.leftButton.backgroundColor = [UIColor whiteColor];
    }
}

#pragma Top Button
- (void)setButton
{
    self.leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _leftButton.frame = CGRectMake(0, 0, WIDTH / 2, 54);
    [_leftButton addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    [_leftButton setTitle:@"单品" forState:UIControlStateNormal];
    [self.searchView addSubview:_leftButton];
    _leftButton.backgroundColor = [UIColor cyanColor];
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _rightButton.frame = CGRectMake(WIDTH / 2, 0, WIDTH /2, 54);
    [_rightButton addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    [_rightButton setTitle:@"专题" forState:UIControlStateNormal];
    [self.searchView addSubview:_rightButton];
}

#pragma mark Button Click Method
- (void)Button:(UIButton *)sender
{
    if (sender == self.leftButton) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
        self.leftButton.backgroundColor = [UIColor cyanColor];
        self.rightButton.backgroundColor = [UIColor whiteColor];
    } else {
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        self.rightButton.backgroundColor = [UIColor cyanColor];
        self.leftButton.backgroundColor = [UIColor whiteColor];
    }
}



#pragma mark Search Results Of TableView Setting
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height - 110) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.rowHeight = 150;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = NO;
}

#pragma mark TableView Delegate Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    HZMsinTopicTVC *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[HZMsinTopicTVC alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
    }
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.topicArr[indexPath.row] pic]]];
    
    NSMutableAttributedString *attrituteStr = [[NSMutableAttributedString alloc] initWithString:[self.topicArr[indexPath.row] searchResultsTitle_topic]];
    NSRange range = [[self.topicArr[indexPath.row] searchResultsTitle_topic ] rangeOfString:self.searchBar.text];
    [attrituteStr setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:18.0]} range:range];
    
    cell.titleLabel.attributedText = attrituteStr;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.topicArr[indexPath.row] topicType] isEqualToString:@"0"]) {
        HZMTableDetailsVC *tableVC = [[HZMTableDetailsVC alloc] init];
        tableVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:tableVC animated:YES];
        tableVC.urlStr = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445332782.662591&app_versions=4.2.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&screensize=1242&statistics_uv=1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.topicArr[indexPath.row] topicId]];
        [self.searchBar resignFirstResponder];
    } else {
        HZMTableDetailsType1VC *type = [[HZMTableDetailsType1VC alloc] init];
        type.strUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445332782.662591&app_versions=4.2.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&screensize=1242&statistics_uv=1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.topicArr[indexPath.row] topicId]];
        type.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:type animated:YES];
        [self.searchBar resignFirstResponder];
    }
}



#pragma mark SearchResultsCollectionView Setting
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake((WIDTH - 20) / 2, HEIGHT / 3);
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing = 1;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 164) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.collectionView];
    [_collectionView release];
    
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[HZMProductCVC class] forCellWithReuseIdentifier:@"productCVC"];
}

#pragma mark Search Data
- (void)createSearchData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *searchUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/base/search/initData?app_installtime=1445332782.662591&app_versions=4.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [manager GET:searchUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dic = responseObject;
        if ([dic[@"data"][@"topic"]count] == 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"无效搜索" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:ok];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            self.productArr = [NSMutableArray array];
            self.topicArr = [NSMutableArray array];
        
            self.productArr = [HZMProduct baseModelByArr:dic[@"data"][@"product"]];
            self.topicArr = [HZMTopic baseModelByArr:dic[@"data"][@"topic"]];
        
            [self.collectionView reloadData];
            [self.tableView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
}



#pragma mark CollectionView Setting
- (void)createCollection
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(WIDTH / 2, (HEIGHT - 128) / 8);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 2;
    
    self.collection = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
    self.collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collection];
    [_collection release];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.collection registerClass:[HZMSearchCollectionViewCell class] forCellWithReuseIdentifier:@"collectionReuse"];
    
}

#pragma mark CollectionView Delegate Method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.collectionView) {
        return self.productArr.count;
    } else {
    return self.searchArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collection) {
        HZMSearchCollectionViewCell *cell = [self.collection dequeueReusableCellWithReuseIdentifier:@"collectionReuse" forIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:(NSString *)[self.searchArr[indexPath.row] icon]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
        cell.headLabel.text = [self.searchArr[indexPath.row] name];
        cell.footLabel.text = [self.searchArr[indexPath.row] en_name];
        
        return cell;
    } else {
        HZMProductCVC *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"productCVC" forIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.productArr[indexPath.row] pic]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
        cell.priceLabel.text = [NSString stringWithFormat:@"🐑%@", [self.productArr[indexPath.row] price]];
        
        NSMutableAttributedString *attrituteStr = [[NSMutableAttributedString alloc] initWithString:[self.topicArr[indexPath.row] searchResultsTitle_topic]];
        NSRange range = [[self.topicArr[indexPath.row] searchResultsTitle_topic ] rangeOfString:self.searchBar.text];
        [attrituteStr setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:18.0]} range:range];
        cell.titleLabel.attributedText = attrituteStr;
        return cell;
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collection) {
        [self.searchBar resignFirstResponder];// 放弃第一响应者
        self.searchBar.hidden = YES;
        [self.view bringSubviewToFront:self.navigationController.view];
        //    [self.navigationController setNavigationBarHidden:NO animated:YES];
        
        HZMIconDetailsVC *icon = [[HZMIconDetailsVC alloc] init];
        icon.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:icon animated:YES];
        icon.category = [self.searchArr[indexPath.row] iconId];
        icon.iconTitle = [self.searchArr[indexPath.row] name];
        [icon release];
        
    } else {
        HZMSearchDetailsVC *list = [[HZMSearchDetailsVC alloc] init];
        [self.navigationController pushViewController:list animated:YES];
        
        [self.searchBar resignFirstResponder];
    }
}



#pragma mark Internet Data
- (void)createData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"client_secret"] = @"9c1e6634ce1c5098e056628cd66a17a5";
    dic[@"client_id"] = @"bt_app_ios";
    [manager POST:@"http://open3.bantangapp.com/category/list" parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dic = responseObject;
        self.searchArr = [NSMutableArray array];
        self.searchArr = [HZMSearchIcon baseModelByArr:dic[@"data"]];
        
        [self.collection reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
}



- (void) createNetWork {
    AFNetworkReachabilityManager *manager =  [AFNetworkReachabilityManager sharedManager];
    [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        [self showNetWorkWithStatus:status];
        
    }];
}

- (void) showNetWorkWithStatus:(NSInteger)status {
    NSString *str;
    switch (status) {
        case AFNetworkReachabilityStatusUnknown:
            str = @"未知网络";
            //            [self.hud removeFromSuperview];
            break;
        case AFNetworkReachabilityStatusNotReachable:
            str = @"网络未连接";
            
            //            [self.hud removeFromSuperview];
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
            str = @"网络已连接";
            [self createData];
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
            str = @"wlfi已连接";
            [self createData];
            break;
        default:
            break;
    }
    //    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前网络状态" message:str preferredStyle:UIAlertControllerStyleAlert];
    //    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    //    [alert addAction:cancel];
    //    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
